package com.ruicar.afs.cloud.channel.common.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.channel.common.mq.sender.SenderChannelToApply;
import com.ruicar.afs.cloud.channel.common.mq.sender.config.CommissionConfig;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.ChannelIdToCommissionSystemImpl;
import com.ruicar.afs.cloud.channel.common.mq.sender.impl.SenderChannelToArchiveImpl;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.job.core.biz.model.ReturnT;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJob;
import com.ruicar.afs.cloud.common.job.core.handler.annotation.AfsJobHandler;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.image.config.GwtFastdfsProperties;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleDetail;
import com.ruicar.afs.cloud.parameter.commom.entity.TsysVehicleModel;
import com.ruicar.afs.cloud.parameter.commom.entity.VeBrand;
import com.ruicar.afs.cloud.parameter.commom.entity.VeMain;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleDetailService;
import com.ruicar.afs.cloud.parameter.commom.service.TsysVehicleModelService;
import com.ruicar.afs.cloud.parameter.commom.vo.VeBrandVo;
import com.ruicar.afs.cloud.parameter.commom.vo.VeMainVo;
import com.ruicar.afs.cloud.vehicle.dto.CarInfoDto;
import com.ruicar.afs.cloud.vehicle.feign.VehicleApiFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Ice
 * @date 2020/9/22 18:39
 */
@AfsJob
@AllArgsConstructor
@Slf4j
@Component
public class VehicleTask {
    private final SenderChannelToApply senderChannelToApply;
    private VehicleApiFeign vehicleApiFeign;
    private final TsysVehicleDetailService tsysVehicleDetailService;
    private ChannelIdToCommissionSystemImpl channelIdToCommissionSystem;


    private final SenderChannelToArchiveImpl senderChannelToArchive;
    private TsysVehicleModelService tsysVehicleModelService;

    @Transactional(rollbackFor = Exception.class)
    @AfsJobHandler(value = "autoVehicleTask")
    public ReturnT<String> synchro(String params) throws ParseException {
        // 查询车型库最新的时间
        List<TsysVehicleDetail> details = tsysVehicleDetailService.list(Wrappers.<TsysVehicleDetail>query().lambda().orderByDesc(TsysVehicleDetail::getUpdateTime));
        if (details.size() <= 0) {
            throw new AfsBaseException("系统暂无车型库数据！");
        }
        CarInfoDto dto = new CarInfoDto();
        dto.setVersion(details.get(0).getUpdateTime().getTime());
        JSONObject json = vehicleApiFeign.brandAndCode(dto);
        if ("0".equals(json.get("code").toString())) {
            JSONObject data = json.getJSONObject("data");
            List<VeBrand> veBrand = data.getJSONArray("veBrandList").toJavaList(VeBrand.class);
            List<VeMain> veMain = data.getJSONArray("veMainList").toJavaList(VeMain.class);
            // 说明返回成功
            if (veBrand.size() > 0 || veMain.size() > 0) {
                //  同步自己的数据
                this.synchroVehicle(veBrand, veMain);
                // 同步到进件

                if (veBrand.size() > 0) {
                    VeBrandVo brandVo = new VeBrandVo();
                    brandVo.setVeBrandList(veBrand);
                    AfsTransEntity<VeBrandVo> transEntity = new AfsTransEntity();
                    transEntity.setTransCode(MqTransCode.CHANNEL_CHANNEL_APPLY_POS_SEND_VEHICLE_BRAND_APPLY);
                    transEntity.setData(brandVo);
                    senderChannelToApply.sendSynchroBrand(transEntity);
                }
                if (veMain.size() > 0) {
                    VeMainVo mainVo = new VeMainVo();
                    mainVo.setVeMainList(veMain);
                    AfsTransEntity<VeMainVo> transEntity = new AfsTransEntity();
                    transEntity.setTransCode(MqTransCode.CHANNEL_CHANNEL_APPLY_POS_SEND_VEHICLE_MAIN_APPLY);
                    transEntity.setData(mainVo);
                    senderChannelToApply.sendSynchroMain(transEntity);
                }

            }
        }
        return ReturnT.SUCCESS;
    }

    public void synchroVehicle(List<VeBrand> brands, List<VeMain> mains) throws ParseException {
        DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(brands.size()>0){
            for (VeBrand brand:brands){
                TsysVehicleModel model = tsysVehicleModelService.getOne(Wrappers.<TsysVehicleModel>query().lambda()
                        .eq(TsysVehicleModel::getCode,brand.getCode()));
                if(model==null){
                    // 说明没有 我要去添加
                    TsysVehicleModel m=new TsysVehicleModel();
                    m.setCode(brand.getCode());
                    m.setModels(brand.getBrand());
                    m.setBrandCode(brand.getMaker());
                    if(brand.getOrderid()!=null&&brand.getOrderid()!=""){
                        m.setOrderId(Integer.valueOf(brand.getOrderid()));
                    }
                    m.setIsActive(brand.getIsactive());
                    m.setStyleRule(brand.getStylerule());
                    m.setFullName(brand.getFullname());
                    m.setCmsId(brand.getCmsid());
                    m.setType(brand.getType());
                    m.setSeriesId(brand.getSeriesid());
                    m.setAdditionalTag(brand.getAdditionaltag());
                    m.setNeedSync(brand.getNeedsync());
                    m.setCreateBy(brand.getCreateuser());
                    m.setUpdateBy(brand.getUpdateuser());
                    m.setDelFlag(brand.getIsdelete());
                    m.setCreateTime(new Date(System.currentTimeMillis()));
                    m.setUpdateTime(new Date(System.currentTimeMillis()) );
                    tsysVehicleModelService.save(m);

                    // 去同步佣金
                    String ss= channelIdToCommissionSystem.AssembledVehicleType(brand.getBrand(),brand.getCode(),brand.getType(),brand.getFullname());
                    channelIdToCommissionSystem.sendAlterDealerMq(m.getId().toString(), CommissionConfig.TABLECODE_VEBRAND,CommissionConfig.ACTION_ADD,ss);
                }else {
                    // 说明存在去更新
                    model.setCode(brand.getCode());
                    model.setModels(brand.getModels());
                    model.setBrandCode(brand.getMaker());
                    if(brand.getOrderid()!=null&&brand.getOrderid()!=""){

                        model.setOrderId(Integer.valueOf(brand.getOrderid()));
                    }
                    model.setIsActive(brand.getIsactive());
                    model.setStyleRule(brand.getStylerule());
                    model.setFullName(brand.getFullname());
                    model.setCmsId(brand.getCmsid());
                    model.setType(brand.getType());
                    model.setSeriesId(brand.getSeriesid());
                    model.setAdditionalTag(brand.getAdditionaltag());
                    model.setNeedSync(brand.getNeedsync());
                    model.setCreateBy(brand.getCreateuser());
                    model.setUpdateBy(brand.getUpdateuser());
                    model.setDelFlag(brand.getIsdelete());
                    model.setUpdateTime(new Date(System.currentTimeMillis()));
                    tsysVehicleModelService.updateById(model);

                    String ss= channelIdToCommissionSystem.AssembledVehicleType(brand.getBrand(),brand.getCode(),brand.getType(),brand.getFullname());
                    channelIdToCommissionSystem.sendAlterDealerMq(model.getId().toString(),CommissionConfig.TABLECODE_VEBRAND,CommissionConfig.ACTION_EDIT,ss);
                }
            }
        }
        if(mains.size()>0){
            for (VeMain main:mains){
                TsysVehicleDetail detail =tsysVehicleDetailService.getOne(Wrappers.<TsysVehicleDetail>query().lambda()
                        .eq(TsysVehicleDetail::getCode,main.getCode()).eq(TsysVehicleDetail::getModelCode,main.getBrandcode()));
                if(detail==null){
                    TsysVehicleDetail t =new TsysVehicleDetail();
                    t.setModelCode(main.getBrandcode());
                    t.setCode(main.getCode());
                    t.setName(main.getName());
                    if(main.getGuideprice()!=null){
                        t.setGuidePrice(new BigDecimal(main.getGuideprice()));
                    }
                    t.setIsActive(main.getIsactive());
                    if(main.getOrderid()!=null&&main.getOrderid()!=""){
                        t.setOrderId(Integer.valueOf(main.getOrderid()));
                    }
                    t.setDisplacement(main.getVehiclemain05());
                    t.setTransmission(main.getVehiclemain06());
                    t.setConfigure(main.getVehiclemain07());
                    t.setYearStyle(main.getYearstyle());
                    t.setAssetsCode(main.getZichancode());
                    t.setPowerType(main.getDonglitype());
                    t.setDriver(main.getDriver());
                    t.setBlowoff(main.getPaifang());
                    t.setCmsId(main.getCmsid());
                    t.setRedBlue(main.getVemain01());
                    t.setMemo(main.getMemo());
                    t.setInterior(main.getVemain02());
                    t.setModelId(main.getModelid());
                    t.setChe300Style(main.getChe300style());
                    if(main.getChelong()!=null){
                        t.setCarLength(new BigDecimal(main.getChelong()));
                    }
                    if(main.getWight()!=null){
                        t.setWight(new BigDecimal(main.getWight()));
                    }
                    if(main.getSeatnum()!=null){
                        t.setSeatNum(new BigDecimal(main.getSeatnum()));
                    }
                    t.setCarLevel(main.getCarlevel());
                    t.setIsParallel(main.getIsparallel());
                    t.setNeedSync(main.getNeedsync());
                    t.setIsInternet(main.getIschelianwag());
                    t.setIsGreen(main.getIsgreen());
                    t.setCarType(main.getCartype());
                    t.setCarTypeDetail(main.getCartypedetail());
                    t.setUpdateTime(fmt.parse(main.getUpdatedate()));
                    t.setUpdateBy(main.getUpdateuser());
                    t.setCreateBy(main.getCreateuser());
                    t.setCreateTime(new Date(System.currentTimeMillis()));
                    t.setUpdateTime(new Date(System.currentTimeMillis()));
                    tsysVehicleDetailService.save(t);
                    // 同步到佣金
                    String ss= channelIdToCommissionSystem.AssemblyModelData(t.getName(),t.getCode());
                    channelIdToCommissionSystem.sendAlterDealerMq(t.getId().toString(),CommissionConfig.TABLECODE_SSCODE,CommissionConfig.ACTION_ADD,ss);
                }else {
                    detail.setModelCode(main.getBrandcode());
                    detail.setCode(main.getCode());
                    detail.setName(main.getName());
                    if(main.getGuideprice()!=null){
                        detail.setGuidePrice(new BigDecimal(main.getGuideprice()));
                    }
                    detail.setIsActive(main.getIsactive());
                    if(main.getOrderid()!=null&&main.getOrderid()!=""){
                        detail.setOrderId(Integer.valueOf(main.getOrderid()));
                    }
                    detail.setDisplacement(main.getVehiclemain05());
                    detail.setTransmission(main.getVehiclemain06());
                    detail.setConfigure(main.getVehiclemain07());
                    detail.setYearStyle(main.getYearstyle());
                    detail.setAssetsCode(main.getZichancode());
                    detail.setPowerType(main.getDonglitype());
                    detail.setDriver(main.getDriver());
                    detail.setBlowoff(main.getPaifang());
                    detail.setCmsId(main.getCmsid());
                    detail.setCreateTime(fmt.parse(main.getCdate()));
                    detail.setRedBlue(main.getVemain01());
                    detail.setMemo(main.getMemo());
                    detail.setInterior(main.getVemain02());
                    detail.setModelId(main.getModelid());
                    detail.setChe300Style(main.getChe300style());
                    if(main.getChelong()!=null){
                        detail.setCarLength(new BigDecimal(main.getChelong()));
                    }
                    if(main.getWight()!=null){
                        detail.setWight(new BigDecimal(main.getWight()));
                    }
                    if(main.getSeatnum()!=null){
                        detail.setSeatNum(new BigDecimal(main.getSeatnum()));
                    }
                    detail.setCarLevel(main.getCarlevel());
                    detail.setIsParallel(main.getIsparallel());
                    detail.setNeedSync(main.getNeedsync());
                    detail.setIsInternet(main.getIschelianwag());
                    detail.setIsGreen(main.getIsgreen());
                    detail.setCarType(main.getCartype());
                    detail.setCarTypeDetail(main.getCartypedetail());
                    detail.setUpdateBy(main.getUpdateuser());
                    detail.setCreateBy(main.getCreateuser());
                    detail.setUpdateTime(new Date(System.currentTimeMillis()));
                    tsysVehicleDetailService.updateById(detail);

                    String ss= channelIdToCommissionSystem.AssemblyModelData(detail.getName(),detail.getCode());
                    channelIdToCommissionSystem.sendAlterDealerMq(detail.getId().toString(),CommissionConfig.TABLECODE_SSCODE,CommissionConfig.ACTION_EDIT,ss);
                }
            }
        }

    }
}